#include <func.h>
/*
    进程A的聊天发送界面
*/

struct sharedMem
{
    int written; // 0表示可读，1表示可写
    char text[128];
};

int main(int argc, char* argv[])
{
    // 收发管道设置
    int fdr = open("1.pipe", O_RDONLY);
    ERROR_CHECK(fdr, -1, "open");
    int fdw = open("2.pipe", O_WRONLY);
    ERROR_CHECK(fdw, -1, "open");

    // 显示管道设置
    int fdw1 = open("3.pipe", O_WRONLY);
    ERROR_CHECK(fdw1, -1, "open");

    // 共享内存申请
    int shmid;
    shmid = shmget(1000,4096,IPC_CREAT|0600);//第一次创建，第二次相同的key值是获取
    ERROR_CHECK(shmid,-1,"shmget");
    struct sharedMem *share = (struct sharedMem*)shmat(shmid,NULL,0);//共享内存连接到本进程内
    // ERROR_CHECK(p,(struct sharedMem *)-1,"shmat");


    char buf[128] = {0}; // 管道信息
    fd_set fd;
    int ret;
    while (1)
    {
        FD_ZERO(&fd);
        FD_SET(STDIN_FILENO, &fd);
        FD_SET(fdr, &fd);

        select(fdr + 1, &fd, NULL, NULL, NULL);

        // 发
        if (FD_ISSET(STDIN_FILENO, &fd))
        {
            memset(buf, 0, sizeof(buf));
            ret = read(STDIN_FILENO, buf, sizeof(buf));
            // 我想结束聊天
            if (ret == 0) // ctrl d
            {
                // printf("I want to leave\n");
                break;
            }
            write(fdw, buf, strlen(buf) - 1);
        }

        // 收
        if (FD_ISSET(fdr, &fd))
        {
            memset(buf, 0, sizeof(buf));
            ret = read(fdr, buf, sizeof(buf));
            
            if (share->written == 1)
            {
                strcpy(share->text, buf);
                if (ret == 0) strcpy(share->text, "end");
                share->written = 0;
            }
            if (ret == 0) break;
        }
    }
    // 关闭管道
    close(fdr);
    close(fdw);
    close(fdw1);

    // 删除共享内存
    shmctl(shmid, IPC_RMID, NULL);
    return 0;
}
